package com.zzy.sercice.impl;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.zzy.dto.RequesParams;
import com.zzy.sercice.aiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.lang.System;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

@Service
@Slf4j
public class AiSerivceImpl implements aiService {
    final String DASHSCOPE_API_KEY = "sk-0867449b3862467ab16b4b92dd8edb6e";

    @Override
    public String handleQuestion(RequesParams requesParams) {
        try {
            GenerationResult result = callWithMessage(requesParams);
            String json = JsonUtils.toJson(result);
            JsonObject parse = JsonUtils.parse(json);
            JsonObject output = parse.getAsJsonObject("output");
            JsonArray choices = output.getAsJsonArray("choices");
            JsonObject firstChoice = choices.get(0).getAsJsonObject();
            JsonObject message = firstChoice.getAsJsonObject("message");
            return message.get("content").getAsString();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // 使用日志框架记录异常信息
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        return "";
    }

    public GenerationResult callWithMessage(RequesParams requesParams) throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(requesParams.getQuestion())
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(DASHSCOPE_API_KEY)
                // 此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
                .model("qwen1.5-110b-chat")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        log.info("param: {}", param);
//        获取当前时间并格式化成 yyyy:MM:dd hh:MM:ss
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = dateFormat.format(System.currentTimeMillis());
        log.info("开始调用ai"+startTime);
        GenerationResult call = gen.call(param);
        String endTime = dateFormat.format(System.currentTimeMillis());
        log.info("结束调用ai"+endTime);
        return call;
    }

}
